<?php
class PostData {
    static public function post($url, $data) {
        $_data = $data;
        unset($_data["action"]);
        unset($_data["page_id"]);
        unset($_data["PHPSESSID"]);
        unset($_data["ECS"]);


        //headers
        $headers = self::getHeaders($url);
        //var_dump($headers);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, self::dataEncode($_data));
        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        $content = curl_exec($ch);

if(FALSE === $content){
echo "<br>";
echo __FILE__ . ', line: '. __LINE__ . ': ';
echo "<br>";
echo "Error Code:" . curl_errno($ch);

echo "<br>";
echo "Error Info:" . curl_error($ch);
echo "<br>";
}
        
        //var_dump($content);
        return $content;
    }
    
    static public function dataEncode($data) {
        assert(is_array($data));
        $vars = "";
        foreach ($data as $key=>$value) {
            if(is_array($value)) {
                foreach ($value as $subKey=>$subValue) {
                		if (is_array($subValue)) {
                			foreach ($subValue as $ssubKey=>$ssubValue) {
                				  $vars .= $key."[$ssubKey][$subKey]=".urlencode($ssubValue)."&";
                			}
                		}else {
                    $vars .= $key."[$subKey]=".urlencode($subValue)."&";
                		}
                }
            } else {
                $vars .= $key."=".urlencode($value)."&";
            }
        }
        return rtrim($vars, "&");
    }
    
    static public function getHeaders($url) {
        $temp = parse_url($url);
        $query = isset($temp['query']) ? $temp['query'] : '';
        $cookies= '';
        if(count($_COOKIE)) {
            foreach($_COOKIE as $cookie_name => $cookie_var) {
                $cookies .= $cookies != '' ? ('; '.$cookie_name.'='.$cookie_var):($cookie_name.'='.$cookie_var);
            }
        }
        $path = isset($temp['path']) ? $temp['path'] : '/';
        $headers = array(
            "POST {$path}?{$query} HTTP/1.1",
            "Host: {$temp['host']}",
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language: zh-cn,zh;q=0.5',
            'Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7',
            "Referer: http://{$temp['host']}/",
            "Cookie: $cookies",
            'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.20) Gecko/20110803 Firefox/3.6.20',
            "Connection: Close"
        ); 
        return $headers;
    }
}